import { redisClient } from "../db/redis/index.js";

const clientsKey = "clients";

// 保存客户端信息
export async function saveClient(client) {
  try {
    const result = await redisClient.hset(
      clientsKey,
      client.id,
      JSON.stringify(client)
    );
    if (result) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}

// 获取客户端信息
export async function getClient(userId) {
  try {
    const result = await redisClient.hget(clientsKey, userId);
    if (result) {
      return JSON.parse(result);
    } else {
      return null;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}

// 删除客户端信息
export async function deleteClient(userId) {
  try {
    const result = await redisClient.hdel(clientsKey, userId);
    if (result) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}

// 获取所有客户端信息
export async function getAllClients() {
  try {
    const result = await redisClient.hgetall(clientsKey);
    if (result) {
      const clients = [];
      for (const key in result) {
        clients.push(JSON.parse(result[key]));
      }
      return clients;
    } else {
      return null;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
